//
//  FImages.swift
//  dypart
//
//  Created by zhuxietong on 2021/3/12.
//

import Foundation
import Eelay
import TZImagePickerController


open class FImageKit:GridCol{
    public let addBt = ASButtonNode()
    public let deleteBt = ASButtonNode()
    public let imgN = JoImageNode()
    public var isAdd:Bool{
        return mo.model["isAdd",""] == "YES"
    }
    
    
    open override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
        var item = super.hitTest(point, with: event)

        if item == nil{
            let p:CGPoint = self.view.convert(point, to: deleteBt.view)
            if deleteBt.view.bounds.contains(p){
                item = deleteBt.view
            }

        }
        return item
    }

    
    open override func addLayoutRules() {
        addBt.actionID = "add"
        deleteBt.actionID = "delete"
        deleteBt.imageNode.contentMode = .scaleAspectFit

        deleteBt.setImage(UIImage(named: "f_img_delete"), for: .normal)
        addBt.addTarget(self, action: #selector(buttonAction(sender:)), forControlEvents: .touchUpInside)
        deleteBt.addTarget(self, action: #selector(buttonAction(sender:)), forControlEvents: .touchUpInside)
        
        imgN.bsui.set(radius: 5, width: 1, color: UIColor._separator.alpha(0.4))
        addBt.imageNode.contentMode = .scaleAspectFit
        addBt.contentMode = .scaleAspectFit

    }
    open override func mo_model_reload() {
        let src = mo.model["src"]
        if let url = src as? String{
            imgN.img_url = url
        }
        if let img = src as? UIImage{
            imgN.image = img
        }
        if isAdd{
            setAddImage()
        }
    }
    
    open func setAddImage(){
        addBt.setBackgroundImage(UIImage(named: "f_img_add"), for: .normal)

    }
    
    
    @objc open func buttonAction(sender:ASButtonNode){
        delegate?.active(onwer: self, actionID: sender.actionID, data: mo.model)
    }

    
    open override func specGetter() -> _Spec {

        if !isAdd{
            return imgN[width,"\(height)"].addOver(.inset([], [-6], child: .stack(["h",_justfy(.space_between)], childs: [
                .stack([], childs: []),
                deleteBt["20",20]
            ])))
        }
        
        return addBt[width,"\(height)"]
    }
}


open class FImagesBase:FField,AsyncTask{
    //-------AsyncTask start ------

    public var asyncQueIndex: Int = 0
    
    public var asyncStatus: TaskStatus = .waiting
    
    public var asyncDelegate: AsyncTaskDelegate? = nil
    
    open func startTask() {
        fatalError("请完善 startTask 逻辑才内进行异步上传")
    }
    public func canleTask() {
        self.finish(success: false, objs: "已取消")
    }
    public func finish(success: Bool, objs: Any...) {
        if success{
            self.asyncStatus = .success
        }
        else{
            self.asyncStatus = .failed
        }
        asyncDelegate?.finish(task: self)
    }
    
    //-------AsyncTask end------
    
    
    
}
open class FImages<Kit:FImageKit>:FImagesBase,TZImagePickerControllerDelegate, EeActionDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate{
    //-------AsyncTask start ------


    
    //-------AsyncTask end------
    
    
    public var remoteValues:(Any)? = nil

    
//    public override var defaultProps: [FProps]{
//        get{
//
//
//            return [.type(.select),.verify(.reg("\\S+"))]
//        }
//    }
    open override var defaultProps: [FProps]{
        get{
            let v:FVerify = .method {[weak self] (v) -> FVerifyResult in
                guard let `self` = self else{return .success(value: v)}
                let limit = self.props.num_limit
                var list:[Any] = []
                if let strV = v as? String{
                    list = strV.split(separator: ",")
                }
                
              
                if list.count < limit.min{
                    return .error(limit.minMask)
                }
                if list.count > limit.max{
                    return .error(limit.maxMask)
                }
                return .success(value: v)
            }
            return [.type(.select),.verify(v)]
        }
    }
    
 
    
    
    
    public func active(onwer: Any, actionID: String, data: NSMutableDictionary) {
//        print("00000S",actionID)
        
        if actionID == "delete"{
            if let kit = onwer as? Kit{
                let i = kit.index
                var values = images
                values.remove(at: i)
                update(value: values, edit: .select)
            }
        }
        
        if actionID == "add" {
            toSelectImg()
        }
        
        if actionID == "preview" {
            if let kit = onwer as? Kit{
                preview(item: kit)
            }
        }
    }
    
    open func preview(item:Kit){
       
    }
    
    
    
    @objc open func toSelectImg(){
        toTZImagePickerController()
        
    }

    open override var sumbitValue: Any{
        if let remote = remoteValues{
            return remote
        }
        let kits = self.listV.items.filter{!$0.isAdd}
        return kits.map{$0.mo.model["src"]}.filter{$0 != nil}
    }
    
    
//    open var images:[Any]{
//        var values:[Any] = []
//        if let vs = self.sumbitValue as? [Any]
//        {
//            values = vs
//        }
//        if let vs = self.sumbitValue as? String
//        {
//            values = vs.split(separator: ",")
//        }
//        return values
//    }
    open var images:[Any]{
        var values:[Any] = []
        if let vs = self.value as? [Any]
        {
            values = vs
        }
        if let vs = self.value as? String
        {
            if vs.hasPrefix("["){
                values = vs.JsonArray?.swift_array ?? []
            }else{
                values = vs.split(separator: ",")
            }
        }
        return values
    }
    
    public let listV = GridNode<Kit,ASDisplayNode>()
    
    open override func addLayoutRules() {
        super.addLayoutRules()
        listV.columnCount = 4
        listV.rowHeight = .scale(1)
        listV.space = (8,8)
        listV.padding = [10,0]
        listV.delegate = self
        listV.limtWidth = Swidth - 2 * .hpadding
        listV.didLoadKits = {[weak self] kits in
            guard let `self` = self else{return}
            self.changeFrame.onNext(self)
            self.didLoadKis(kits: kits)
        }
        
    }
    
    open func didLoadKis(kits:[MoDisplayNode]){
        self.changeFrame.onNext(self)
    }
    
    
    open override func update(_ prop:FProps){
        props.update(prop)
        loadProps()
    }


    open override func updateDispaly() {

        var imgs = [Any]()
        if let imgs_ = self.value as? String{
            imgs = imgs_.split(separator: ",")
        }
        if let imgs_ = self.value as? [Any]{
            imgs = imgs_
        }
        if let imgs_ = self.value as? NSMutableArray{
            var strs:[Any] = []
            for item in Each<String>(imgs_) {
                strs.append(item)
            }
            imgs = strs

        }
        var array = imgs.map{["src":$0]}
        
        if imgs.count < props.num_limit.max {
            array.append(["isAdd":"YES"])
        }
        mo.model[listV.nodePath] = array.mutable_array
        listV.mo.model = mo.model
   
        
    }
    
    open override func specGetter() -> _Spec {
        return .inset([], .zero, child: .stack(["v|6",&-.stretch], childs: [
            lableNode.Spec,
            listV.Spec
        ]))
    }
    @objc open func chooseImg()
    {
        mo.controller?.view.endEditing(true)

        
        MoDialog().title(placeholder).message("请拍照或从相册选择图片").append(name: "拍照", action: {[weak self] (alert) in
            self?.selectImage(index: 0)
            alert?.hidden()
        }, style: .confirm).append(name: "相册", action: {[weak self] (alert) in
            self?.selectImage(index: 1)
            alert?.hidden()
        }, style: .confirm).append(name: "取消", action: { (alert) in
            alert?.hidden()
        }, style: .cancel).sheet.touchClose(true).show(at: mo.controller)
        
//        weak var wself = self
//        JoAlertView(info: "提示".loc,"选择图片".loc,"取消".loc).append(title: "拍照".loc, action: {wself?.selectImage(index: 0)}).append(title: "图库选择".loc, action: {wself?.selectImage(index: 1)}).sheet.show(at: mo.controller)

    }
    open override func update(value: Any, edit: FEdit) {
        switch edit {
        case .input,.select,.fill:
            remoteValues = nil
        default:
            break
        }
        super.update(value: value, edit: edit)
    }
    
    
    open func selectImage(index:NSInteger)
    {
        let picker:UIImagePickerController = UIImagePickerController()
        picker.delegate = self
        if index == 1
        {
            picker.sourceType = UIImagePickerController.SourceType.photoLibrary
        }
        else
        {
            picker.sourceType = UIImagePickerController.SourceType.camera
        }
        picker.allowsEditing = true
        picker.modalPresentationStyle = .fullScreen
        mo.controller?.present(picker, animated: true) { () -> Void in
        }
    }

    open func isAssetCanBeSelected(_ asset: PHAsset!) -> Bool {
        return true
    }
//    open func isAssetCanBeDisplayed(_ asset: PHAsset!) -> Bool {
//        return true
//    }
//    
    open func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {

        if let image = info[.originalImage] as? UIImage{
            if var vs = self.images as? [Any]
            {
                vs.append(image)
                update(value: vs, edit: .select)
            }
        }
        picker.dismiss(animated: true) { () -> Void in

        }
    }
    
    
    
    
    open func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {

        picker.dismiss(animated: true) { () -> Void in

        }

    }

    
    open func imagePickerController(_ picker: TZImagePickerController!, didSelect asset: PHAsset!, photo: UIImage!, isSelectOriginalPhoto: Bool) {
        
    }
    
    open func imagePickerController(_ picker: TZImagePickerController!, didDeselect asset: PHAsset!, photo: UIImage!, isSelectOriginalPhoto: Bool) {
        
    }
    
    
    //MARK: TZImagePickerController methods
    open func toTZImagePickerController() {

       
        let max = props.num_limit.max - images.count
        let ctr = TZImagePickerController(maxImagesCount: max, columnNumber: 3, delegate: self, pushPhotoPickerVc: true)
        ctr?.allowTakePicture = true
        ctr?.title = mo.model[FK.placeholder,"选择图片"]
        ctr?.showPhotoCannotSelectLayer = true

        ctr?.modalPresentationStyle = .fullScreen

 
        ctr?.navigationBar.backIndicatorImage = nil
        ctr?.navigationBar.backItem?.backBarButtonItem?.setTitlePositionAdjustment(UIOffset(horizontal: 0, vertical: 0), for: .default)
        ctr?.navigationBar.backIndicatorTransitionMaskImage = UIImage.image(.clear, size: [0.1,0.1])
        ctr?.navigationBar.titleTextAttributes = [NSAttributedString.Key.foregroundColor:UIColor(shex:"#fff"),NSAttributedString.Key.font:UIFont.systemFont(ofSize: 16)]
        ctr?.navigationBar.tintColor = .white
        
        
        let style = EeTopStyle.default

        ctr?.statusBarStyle = style.statusBarStyle
        ctr?.naviBgColor = .color(light: "#f1f1f1", dark: "#222222")
        ctr?.naviTitleColor = .color(light: "#26262", dark: "#f1f1f1")
        ctr?.barItemTextColor = .color(light: "#26262", dark: "#f1f1f1")
        weak var wself = self
        ctr?.didFinishPickingPhotosHandle = {
            (imgs:[UIImage]?,asset:[Any]?,isSelectOriginalPhoto:Bool?) in
            if let list = imgs{
                wself?.addImages(imgs: list)
            }
            
        }

        
        mo.controller?.present(ctr!, animated: true
            , completion: nil)
    }
    
    open func addImages(imgs:[UIImage]) {
        
        var values = self.images
        for img in imgs
        {
            let smallPng = img.commpress(maxSize: 800)
            values.append(smallPng)
            
        }
        self.update(value: values, edit: .select)
    
        //        uploadFiles(files: list)
     
    }
    
    

        
  

}
